<template>
  <el-breadcrumb separator="/" id="breadcrumb">
    <el-breadcrumb-item :to="{ path: '/home/system' }">系统设置</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-row>
    <el-col :span="4" class="main-left">
      <el-input v-model="deptKeyword" placeholder="部门搜索"/>
      <main>
        <el-tree :filter="deptKeyword" @node-click="treeClick" :data="deptTree" default-expand-all
                 :props='{value: "id", label: "label"}'/>
      </main>
    </el-col>
    <el-col :span="20">
      <tableList
          :dict="dict"
          :tableData="tableData"
          :tableConfig="tableConfig"
          @doit="tableDoit"
      />
    </el-col>
  </el-row>

  <drawer
      :dict="dict"
      :drawerData="drawerData"
      :drawerConfig="drawerConfig"
      @doit="drawerDoit"
  />
  <deleteDialog
      :deleteDialogConfig="deleteDialogConfig"
  />
</template>

<script setup lang="ts">
import tableList from '@/components/TableList.vue'
import drawer from '@/components/Drawer.vue'
import deleteDialog from '@/components/DeleteDialog.vue'
import {ref, reactive, onMounted} from 'vue'
import {
  addUser,
  delUser,
  editUser,
  getUserList,
  getUserSelects,
  resetPwdUser
} from "@/api/system/user.ts";
import {createDict} from "@/common/dict.ts";
import {ElMessage} from 'element-plus'
import {numberToString} from "@/common/index.ts";
import config from '@/config.ts'
//table
import {table_config} from './tableConfig.js'

let tableConfig:any = reactive(table_config()) //表格配置
let tableData:any = ref([]) //表格数据
let search:any = reactive({})

let deptTree:any = ref([])
let deptKeyword:any = ref()
//drawer
import {drawer_config} from './drawerConfig.js'
import {getDeptTree} from "@/api/system/dept.ts";


let drawerConfig:any = reactive(drawer_config()) //抽屉配置
const thing:any = { //新建的实体
  "userId": null,
  "deptId": null,
  "username": "",
  "password": "",
  "nickName": "",
  "phonenumber": "",
  "email": "",
  "sex": "0",
  "status": "0",
  "remark": "",
  "postIds": [],
  "roleIds": []
}
let drawerData:any = ref({})
let deleteDialogConfig:any = ref({
  visible: false,
  message: "是否删除",
  alertTitle: "警告",
  confirmText: "确认",
  cancelText: "取消",
  confirmFunction: () => {
  },
  cancelFunction: () => {
  }
}) //删除对话框配置
const dictKey:Array<string> = ['sys_normal_disable', 'sys_user_sex'] //本页面所需要的字典值
let dict:any = reactive({})

onMounted(async () => {
  dict = await createDict(dictKey) //模块字典值初始化
  await dataInit() //数据初始化
})

//数据初始化
async function dataInit() {
  //获取部门tree
  deptTree.value = await getDeptTree()
  //分页数据加载
  let page = {
    pageNum: tableConfig.pageNum,
    pageSize: tableConfig.pageSize,
  }
  let data = Object.assign(page, search)
  //数据初始化
  const r = await getUserList(data)
  tableData.value = r.data
  tableConfig.total = r.total
  //格式化添加修改的表单数据
  drawerConfig.form[9].options = deptTree.value
}

//点击左侧树节点
function treeClick(e) {
  // @ts-ignore
  tell.log('树节点点击', e)
  search.deptId = e.id
  dataInit()
}

let selection:any = ref([]) //多选的数据
//table事件调度中心
async function tableDoit(e) {
  const eventName = e.eventName, val = e.value
  // @ts-ignore
  tell.log('表格事件分析', eventName, val)
  switch (eventName) {
    case 'refresh': //数据重新加载
      await dataInit()
      break;
    case 'add': //新增数据
      let tmpValadd = Object.assign({}, thing) //深度复制，防止污染
      //获取下拉选择
      const selectRsadd = await getUserSelects()
      // tmpVal.depts = deptTree.value
      drawerConfig.form[9].options = deptTree.value
      drawerConfig.form[10].options = await numberToString(selectRsadd.posts, 'postId')
      drawerConfig.form[11].options = await numberToString(selectRsadd.roles, 'roleId')
      drawerData.value = tmpValadd
      drawerConfig.show = true
      break;
    case 'edit': //编辑数据
      let tmpVal = Object.assign({}, val) //深度复制，防止污染
      //获取下拉选择
      const selectRs = await getUserSelects(val.userId)
      tmpVal.postIds = selectRs.postIds
      tmpVal.roleIds = selectRs.roleIds
      // tmpVal.depts = deptTree.value
      drawerConfig.form[9].options = deptTree.value
      drawerConfig.form[10].options = await numberToString(selectRs.posts, 'postId')
      drawerConfig.form[11].options = await numberToString(selectRs.roles, 'roleId')
      drawerData.value = tmpVal
      drawerConfig.show = true
      break;
    case 'selectionChange': //批量选择
      selection.value = val
      break;
    case 'reset': //重置搜索
      deleteDialogConfig.value = {
        visible: true,
        message: `初始密码后，密码为'${config.userResetPwd}'，请尽快修改密码`,
        alertTitle: "警告",
        confirmText: "确认",
        cancelText: "取消",
        confirmFunction: async () => {
          if (val.userName == 'admin') {
            ElMessage({
              message: `超级管理员不能被删除`,
              type: 'success',
            })
          } else {
            let rs = await resetPwdUser(val.userId)
            if (rs.code == 200) {
              ElMessage({
                message: `密码已经初始化，新密码是'${config.userResetPwd}'`,
                type: 'success',
              })
            }
          }
          deleteDialogConfig.value.visible = false
        },
      }
      break;
    case 'del':
      if (val.type != 1){
        deleteDialogConfig.value = {
          visible: true,
          message: "是否删除该用户",
          alertTitle: "警告",
          confirmText: "确认",
          cancelText: "取消",
          confirmFunction: async () => {
            await delUser(val.userId)
            await dataInit()
            deleteDialogConfig.value.visible = false
          }
        }
      }else{
        ElMessage({
          message: `该用户为超级管理员，不能删除`,
          type: 'warning',
        })
      }
      break;
    case 'search': //搜索
      search = val
      await dataInit()
      break;
    case 'handleSizeChange':
      tableConfig.pageSize = val
      await dataInit()
      break
    case 'handleCurrentChange': //点击分页
      tableConfig.pageNum = val
      await dataInit()
      break
    default:
      // @ts-ignore
      tell.log('未知组件事件', eventName, val)
  }
}

//drawer事件调度中心
async function drawerDoit(e) {
  const eventName = e.eventName, val = e.value
  // @ts-ignore
  tell.log('抽屉事件分析', eventName, val)
  switch (eventName) {
    case 'save': //保存数据
      let result:any = ""
      if (val.userId) {
        result = await editUser(val)
      } else {
        delete val.userId
        result = await addUser(val)
      }

      if (result.code == 200) {
        await dataInit()
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        drawerConfig.show = false
      } else {
        ElMessage({
          message: '数据错误，请管理员查看问题',
          type: 'warning',
        })
      }

      break;
    case 'close': //关闭弹窗
      drawerConfig.show = false
      break;
    default:
      // @ts-ignore
      tell.log('未知组件事件', eventName, val)
  }
}
</script>
<style scoped lang="scss">
.content {
  padding-top: 20px;
}
</style>